# -*- coding: utf-8 -*-
# Copyright © 2024 weidongkl <weidongkx@gmail.com>

import logging
from excavator.utils.shell import c_run_cmd
from excavator.utils.jsonutils import read
from excavator.utils.output import ExcavatorJobOutput
from excavator.job.base import Job
from excavator.models.pkg import InstalledRPMs
from excavator.models.report import notify_err, notify_info
from excavator.group import HarvestsGroup

logger = logging.getLogger("excavator.job")


class HarvestsPkg(Job):
    group = HarvestsGroup
    requires = ()
    provides = (InstalledRPMs,)

    def run(self, *args, **kwargs):
        ExcavatorJobOutput.info(self.name, "harvests pkgs")
        logger.info("harvests pkgs")
        cmd = "/usr/bin/excavator-dnf list"
        rc, ro = c_run_cmd(cmd)
        if rc == 0:
            pkgs_file = "/var/lib/excavator/pkg.json"
            data = read(pkgs_file)
            InstalledRPMs.create(items=data)
            notify_info("get pkg list success", self.name)
        else:
            logger.warning("get pkg list failed {}".format(ro))
            notify_err("get pkg list failed {}".format(ro), self.name)
